﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using AgencyEntityLib.BaseEntity;
using Ecopsy.DataTier;
using Ecopsy.Tools;
using Grishko.UI;


public partial class Ctl_ctlTaskEditor : System.Web.UI.UserControl
{
    
    wsTask ws_Task = (wsTask)GlobalConstants.CurrentAgency.WS_FactoryList[WS_FactoryList.wsKey_Task];

    private Func<bool> _OnCancelClick;
    private Func<bool> _OnMyDataChanged;
    /// <summary>
    /// События - Кнопка Save|Cancelf
    /// </summary>
    public Func<bool> OnCancelClick { get { return _OnCancelClick; } set { _OnCancelClick = value; } }
    public Func<bool> OnMyDataChanged { get { return _OnMyDataChanged; } set { _OnMyDataChanged = value; } }

    public string TaskID { get { return hfCurrentTask.Value; } set { hfCurrentTask.Value = value; } }


    protected void Page_Load(object sender, EventArgs e)
    {
        if (null != lvClient.EditItem)
        {

            Ctl_ctlClientListSelector c = (Ctl_ctlClientListSelector)lvClient.EditItem.FindControl("ctlClientListSelector1");
            c.OnSelectedChange = ctlClietEditorl_OnSelectedClick;
            c.OnCancel = ctlClietEditorl_OnCancelClick;
        }
        
    }

    protected string GetHistoryItemAsText(grdTaskHistoryitem Item)
   {
       string res = "Содержание:" + Item.Task.TaskContent + "\n" ;
       if(! string.IsNullOrEmpty (Item.Task.EmplID) )
           res = res + "Исполнитель:" + Item.Task.GetEmployeer().GetFullNameWithDepartmentPosition() + "\n";
       res = res +"Дата окончания:" +Item.Task.dtFinish.ToString("D") + "  " + Item.Task.dtFinish.Hour.ToString() + ":00";  
       return res;
   }


    private  bool CloseClient(Client cl)
    {
        if (null != lvClient.EditItem)
        {            
            if(null!=cl)
                grdTask.Task.ClientID = cl.ID; 
             
        }
      
        lvClient.EditIndex = -1;
        lvClient.DataSource = grdTaskAsList;
        lvClient.DataBind();

        return true;
    }

    protected bool EditEmplEnabled()
    {
        return iPageController.UserInRoleForSiteMapItem(GlobalConstants.SiteMapItem_MangeTask);// позвоено рулить чужими задачами?
    }
    protected override void OnDataBinding(EventArgs e)
    {
        base.OnDataBinding(e);

        lvTaskCategory.DataSource = grdTaskAsList;
        lvTaskCategory.DataBind();
        
 
        lvEmpl.DataSource = grdTaskAsList;
        lvEmpl.DataBind();

        lvClient.DataSource = grdTaskAsList;
        lvClient.DataBind();

        lvDtFinish.DataSource = grdTaskAsList;
        lvDtFinish.DataBind();

        lvHistory.DataSource = grdTaskAsList;
        lvHistory.DataBind();


        //txtTime.Items.Clear();
        //txtTime.Items.AddRange(grdTask.Hours);
    }

    protected void btnSaveTask_Click(object sender, EventArgs e)
    {
        ///Read task
        Task  t = Task;
        t.TaskContent = txtContent.Text ;
        t.IsClosed = chTaskClosed.Checked;

        //сохраняем историю
        if(!iPageController .IsNewRecord (t.ID ))
            {            
                TaskHistoryItem hi = new TaskHistoryItem() { Creator = GlobalConstants.CurrentEmployeer, Date = DateTime.Now, Task = (BaseTask)t.Clone () };
                t.History.Add(hi);
            }

        ws_Task.SaveTask(t);        
        if (_OnCancelClick != null) 
                _OnCancelClick();
    }

    protected bool IsTaskTime(string s)
    {
        if (s == "8") return true;
        return (grdTask.dtFinish.Hour.ToString ().Equals(s));     
        
    }
    protected grdTask grdTask
    {
        get 
        {            
            return new grdTask(Task);
              
        }
    }
    
    protected Task Task
    {
        get 
        {
            return ws_Task.GetTask(TaskID);
        }

        
    }

    protected List <grdTask > grdTaskAsList
    {
        get
        {
             List<grdTask> res=new List<grdTask>();
             res.Add(grdTask);
             return res;
        }
    }
    
 
    protected void BntCancelTask_Click(object sender, EventArgs e)
    {
        if (_OnCancelClick() != null) 
                        _OnCancelClick();      
    }

    private bool UpdateDtFinish(ListViewDataItem item)
    {
        TextBox cl = (TextBox)item.FindControl("txtDtStart");
        DropDownList d = (DropDownList)item.FindControl("cmbTime");
        grdTask.Task.dtFinish = Convert .ToDateTime (cl.Text);
        grdTask.Task.dtFinish = DateTimeTools.ResetTime(grdTask.Task.dtFinish);
        grdTask.Task.dtFinish = grdTask.Task.dtFinish.AddHours(Convert.ToInt16(d.SelectedItem.Text));
        return true;
    }

    private bool UpdateTypeValue(ListViewDataItem item)
    {

        TreeDictionaryControl_Rb tv1 = (TreeDictionaryControl_Rb)lvTaskCategory.EditItem.FindControl("tv_TaskCategory");
        grdTask.Task.TypeValue = tv1.TreeDictionaryItemValue;        
        return true;
    }

    private bool UpdateClient(ListViewDataItem item)
    {
        ListBox txt = (ListBox)lvClient.EditItem.FindControl("lbClientList");
        if (null == txt.SelectedItem) return true;
        this.grdTask.Task.ClientID = txt.SelectedItem.Value;
        if(OnMyDataChanged!=null)OnMyDataChanged();
        return true;
    }

    private bool UpdateHistory(ListViewDataItem item)
    {        
        return true;
    }

    private bool UpdateEmpl(ListViewDataItem item)
    {
        Ctl_ctlEmpCombo ctl = (Ctl_ctlEmpCombo)lvEmpl.EditItem.FindControl("ctlEmpCombo1");
        grdTask.Task.EmplID =ctl.CurrentValue ;         
        return true;
    }

    private Func<ListViewDataItem, bool> LvUpdCmd; 
  

    protected void ItemCommand(object sender, ListViewCommandEventArgs e)
    {
        if (string.Empty == e.CommandName) return;

        ListView lv = (ListView)sender;

        switch (lv.ID)
        {
            case "lvTaskCategory":
                LvUpdCmd = UpdateTypeValue;                 
                break;

            case "lvDtFinish":                 
                LvUpdCmd = UpdateDtFinish;
                 
                break;
            
            case "lvEmpl":
                LvUpdCmd = UpdateEmpl;
                break ;

            case "lvClient":
                     
                LvUpdCmd =UpdateClient ;
                break ;

            case "lvHistory":
                LvUpdCmd = UpdateHistory;
                break;
            
        }

        switch (e.CommandName)
        {
            case "Edit":
                {

                    ListViewDataItem d = (ListViewDataItem)e.Item;
                    lv.EditIndex = d.DataItemIndex;

                    break;
                }
            case "Insert":
                {

                    break;
                }
            case "Update":
                {
                    if (LvUpdCmd((ListViewDataItem)e.Item)) lv.EditIndex = -1;
                   
                    break;
                  
                }
            case "Delete":
                {
                    //DeleteCustomer(e.CommandArgument as string);
                    break;
                }
        }

        lv.DataSource = grdTaskAsList;
        lv.DataBind();


    }

    protected bool GetCategoryCheckBox_Status(TreeEntitySingle _tr)
    {
        return false;
    }

    //событие  Cancel контрола ClietEditor
    private bool ctlClietEditorl_OnCancelClick()
    {
        lvClient.EditIndex = -1;
        lvClient.DataSource = grdTaskAsList;
        lvClient.DataBind();
        return true;
    }

    private bool ctlClietEditorl_OnSelectedClick(Client Client)
    {
        grdTask.Task .ClientID = Client.ID;
        lvClient.EditIndex = -1;
        lvClient.DataSource = grdTaskAsList;
        lvClient.DataBind();        
        return true;

    }
    protected void ItemEditing(object sender, ListViewEditEventArgs e)
    {
        ListView lv = (ListView)sender;
        TreeView tv = null;
        switch (lv.ID)
        {
            case "lvHistory":
            {
                ListView lvHistoryItems = (ListView)lvHistory.EditItem.FindControl("lvHistoryItems");
                lvHistoryItems.DataSource = grdTask.Task.GetHistroyItems() ;
                lvHistoryItems.DataBind();
                break;
                 

            }

            case "lvClient":
                {
                    Ctl_ctlClientListSelector c = (Ctl_ctlClientListSelector)lvClient.EditItem.FindControl("ctlClientListSelector1");
                    c.OnSelectedChange = ctlClietEditorl_OnSelectedClick;
                    c.OnCancel = ctlClietEditorl_OnCancelClick;
                    break;
                }
            case "lvTaskCategory":

                TreeDictionaryControl_Rb tv1 = (TreeDictionaryControl_Rb)lvTaskCategory.EditItem.FindControl("tv_TaskCategory");
                tv1.TreeDictionaryItemValue = (Task.TypeValue == null ? iAdmin_Page.TreeDictionaryContext.GetTaskCategory().BuildValue() : Task.TypeValue);
                tv1.DataBind();    
                break;

            case "lvDtFinish":
                DropDownList cmb = (DropDownList)lv.EditItem.FindControl("cmbTime");
                for (int i = 8; i < 21; i++) { cmb.Items .Add (new ListItem (i.ToString ()));}
                
                if(grdTask .Task .dtFinish .Hour >7&&grdTask .Task .dtFinish .Hour<21)
                {
                    cmb.SelectedIndex = cmb.Items.Count  - (20 - grdTask.Task.dtFinish.Hour);
                    break;
                }
                
                
                break ;
        }
    }
    
    protected void ItemUpdating(object sender, ListViewUpdateEventArgs e)
    {

    }
    
    protected void lvClient_ItemUpdated(object sender, ListViewUpdatedEventArgs e)
    {

    }
   
    protected void lvEmpl_ItemUpdating(object sender, ListViewUpdateEventArgs e)
    {

    }
  
    protected void lvClient_ItemEditing(object sender, ListViewEditEventArgs e)
    {

    }

    protected void SearchClientClick(object sender, EventArgs e)    
    {
        ListBox lb = (ListBox)lvClient.EditItem.FindControl("lbClientList");
        wsFace _ws_Face = (wsFace)GlobalConstants.CurrentAgency.WS_FactoryList[WS_FactoryList.wsKey_Face];
        ClientList.sqlLoadStatment w = new ClientList.sqlLoadStatment();
        w.Lexeme = "";
        ClientList  l = _ws_Face.GetClientList(w);

        Client [] SortResult = l.ToArray<Client>();
        //заряжаем comparer функцией сортировки 
        Ecopsy.Tools.WhereCondition.TSortCondition s = new WhereCondition.TSortCondition() { SortField = "Name" };
        s.fnOrderBy = WhereCondition.SortFunctions.fOrderBy;
        // Сортируем
        Array.Sort(SortResult, s);
        //Заполняем cmb
        foreach (Client item in SortResult)
        {
            ListItem nl = new ListItem(item.Name , item.ID);
            lb.Items.Add(nl);
        }

    }


    protected void BntCancelTask_Click(object sender, ImageClickEventArgs e)
    {
        if (_OnCancelClick != null)
                    _OnCancelClick();
    }
    protected void btnHistory_Click(object sender, EventArgs e)
    {

    }
}
